gpt in affine
runner nix smoke / nix label and flake smoke (push) Failing after 1m12s

This commit is contained in:
2026-11-01 11:21:28 +00:00
parent e935abd0c3
commit 50c4efc09b
30 changed files with 4280 additions and 336 deletions
+3
View File
@@ -0,0 +1,3 @@
.venv
__pycache__/
*.pyc
+41
View File
@@ -0,0 +1,41 @@
# affine-chatgpt
Local ChatGPT OAuth enrollment companion and minimal OpenAI Responses gateway
for AFFiNE. It supports sign-in, safe status inspection, visible-model listing,
text Responses, and client-executed function/custom tools. Gateway runs in
foreground and has no login or administration HTTP endpoints.
```sh
affine-chatgpt login
affine-chatgpt status
affine-chatgpt models
affine-chatgpt serve --gateway-key-file /run/keys/affine-chatgpt
```
`login` binds only `127.0.0.1:1455` (override with `--port`) before printing a
public authorization URL. Open that URL in a local browser and personally
approve access. State defaults to `~/.local/state/affine-chatgpt`; override it
with `--state-dir`. Files are owner-only and must never be copied into the Nix
store, source control, logs, or shared AFFiNE configuration.
`serve` binds `127.0.0.1:3012` by default (`--host` and `--port` override it).
Gateway key file is required, must contain at least 32 characters, and must be
an owner-only regular file. Every `/v1/models` and `/v1/responses` request
requires `Authorization: Bearer <gateway-key>`. `/healthz` returns only generic
readiness. Configure AFFiNE for Responses dialect and choose one of models
returned by `/v1/models`; gateway does not select or invent default model.
Incoming Responses requests are reduced to preview-compatible fields and sent
upstream with `store:false`, `stream:true`, and complete array input history.
Streaming callers receive official SSE events unchanged. Non-stream callers
receive actual terminal completed Response JSON, including text, function
calls, and usage. AFFiNE executes tools and returns `function_call_output` in
next request; gateway never executes tools.
OAuth plan usage remains preview functionality. Supported inputs are text
messages, function-call history/output, and necessary reasoning history.
Function/custom tools are grouped in Responses namespaces. Unsupported:
images/media, files, audio, image generation, file search, Code Interpreter,
hosted MCP/connectors, conversations, background mode, persistent response
continuation, and Chat Completions conversion. No billing fallback exists.
A successful login/model listing does not prove inference entitlement.
+51
View File
@@ -0,0 +1,51 @@
{
lib,
makeWrapper,
stdenvNoCC,
python3,
}:
let
pythonEnv = python3.withPackages (ps: [
ps.requests
ps.pyjwt
ps.cryptography
]);
in
stdenvNoCC.mkDerivation {
pname = "affine-chatgpt";
version = "0.1.0";
src = lib.cleanSourceWith {
src = ./.;
filter = path: type:
!(builtins.elem (builtins.baseNameOf path) [ "__pycache__" ".venv" ]) && !(lib.hasSuffix ".pyc" path);
};
nativeBuildInputs = [ makeWrapper ];
passthru = { inherit pythonEnv; };
doCheck = true;
checkPhase = ''
runHook preCheck
PYTHONPATH="$PWD/src" ${pythonEnv}/bin/python3 -m unittest discover -s test -v
runHook postCheck
'';
installPhase = ''
runHook preInstall
install -Dm444 src/affine_chatgpt.py "$out/share/affine-chatgpt/affine_chatgpt.py"
install -Dm444 src/affine_gateway.py "$out/share/affine-chatgpt/affine_gateway.py"
makeWrapper ${pythonEnv}/bin/python3 "$out/bin/affine-chatgpt" \
--add-flags "$out/share/affine-chatgpt/affine_chatgpt.py" \
--run 'umask 077'
runHook postInstall
'';
meta = {
description = "Local ChatGPT OAuth enrollment companion for AFFiNE";
homepage = "https://developers.openai.com/siwc/token-sharing-open-source/";
license = lib.licenses.mit;
mainProgram = "affine-chatgpt";
platforms = lib.platforms.unix;
};
}
@@ -0,0 +1,5 @@
{
"venvPath": ".",
"venv": ".venv",
"extraPaths": ["src"]
}
@@ -0,0 +1,617 @@
#!/usr/bin/env python3
"""Secure local ChatGPT OAuth enrollment and model discovery."""
import argparse
import base64
import contextlib
import fcntl
import hashlib
import hmac
import ipaddress
import json
import os
import re
import secrets
import stat
import sys
import tempfile
import threading
import time
import uuid
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
from socketserver import ThreadingMixIn
from urllib.parse import parse_qs, urlencode, urlsplit
import jwt
import requests
# The installed wrapper executes this file directly; keep lazy gateway imports
# on the same module instance so expected AppError exceptions remain catchable.
sys.modules.setdefault("affine_chatgpt", sys.modules[__name__])
ISSUER = "https://auth.openai.com"
DISCOVERY_URL = ISSUER + "/.well-known/openid-configuration"
AUTHORIZE_URL = ISSUER + "/api/accounts/authorize"
TOKEN_URL = ISSUER + "/api/accounts/oauth/token"
JWKS_URL = ISSUER + "/.well-known/jwks.json"
RESOURCE = "https://api.openai.com/v1"
MODELS_URL = RESOURCE + "/models"
RESPONSES_URL = RESOURCE + "/responses"
DYNAMIC_CLIENT = "dynamic_agent_client"
AGENT_NAME = "Hearth AFFiNE ChatGPT connector"
SCOPES = "openid profile email offline_access resource.invoke chatgpt.tokens.use.direct"
REQUIRED_SCOPE = "chatgpt.tokens.use.direct"
HTTP_TIMEOUT = 15
SOCKET_TIMEOUT = 5
MAX_CALLBACK = 8192
CLIENT_RE = re.compile(r"^[A-Za-z0-9._~-]{1,256}$")
class AppError(Exception):
"""Expected failure with a non-sensitive stable error code."""
def new_session():
session = requests.Session()
session.trust_env = False
return session
def utc_now():
return datetime.now(timezone.utc).isoformat()
def default_state_dir():
return Path.home() / ".local" / "state" / "affine-chatgpt"
def secure_dir(path):
path = Path(path).expanduser()
try:
info = path.lstat()
except FileNotFoundError:
path.mkdir(parents=True, mode=0o700)
info = path.lstat()
if stat.S_ISLNK(info.st_mode) or not stat.S_ISDIR(info.st_mode):
raise AppError("unsafe_state_dir")
os.chmod(path, 0o700)
return path
def _regular_nofollow(path):
try:
info = Path(path).lstat()
except FileNotFoundError:
return False
if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode):
raise AppError("unsafe_state_file")
if info.st_mode & 0o077:
raise AppError("unsafe_state_file")
return True
def read_json(path):
if not _regular_nofollow(path):
return None
try:
with open(path, "r", encoding="utf-8") as stream:
return json.load(stream)
except (ValueError, TypeError):
raise AppError("invalid_state") from None
def atomic_json(path, value):
path = Path(path)
secure_dir(path.parent)
_regular_nofollow(path)
descriptor, temporary = tempfile.mkstemp(prefix=".tmp-", dir=path.parent)
try:
os.fchmod(descriptor, 0o600)
with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
descriptor = -1
json.dump(value, stream, sort_keys=True, separators=(",", ":"))
stream.write("\n")
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
os.chmod(path, 0o600)
directory_descriptor = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(directory_descriptor)
finally:
os.close(directory_descriptor)
finally:
if descriptor >= 0:
os.close(descriptor)
with contextlib.suppress(FileNotFoundError):
os.unlink(temporary)
def host_id(state_dir, supplied=None):
target = secure_dir(state_dir) / "host.json"
saved = read_json(target)
if saved is not None:
if not isinstance(saved, dict):
raise AppError("invalid_state")
saved_value = saved.get("host_id")
if not isinstance(saved_value, str):
raise AppError("invalid_state")
value = saved_value
elif supplied:
source = Path(supplied).expanduser()
if not _regular_nofollow(source) or source.stat().st_mode & 0o077:
raise AppError("unsafe_host_id_file")
try:
value = source.read_text(encoding="ascii").strip()
except OSError:
raise AppError("invalid_host_id") from None
else:
value = "urn:uuid:" + str(uuid.uuid4())
try:
if not value.startswith("urn:uuid:"):
raise ValueError
parsed = uuid.UUID(value.removeprefix("urn:uuid:"))
if parsed.version != 4:
raise ValueError
except (ValueError, AttributeError):
raise AppError("invalid_host_id") from None
value = "urn:uuid:" + str(parsed)
if saved is None:
atomic_json(target, {"host_id": value})
return value
def pkce_challenge(verifier):
digest = hashlib.sha256(verifier.encode("ascii")).digest()
return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
def _safe_response(response, expected=200):
if response.is_redirect or response.status_code != expected:
raise AppError("oauth_http_error")
try:
value = response.json()
except (requests.RequestException, ValueError):
raise AppError("oauth_response_invalid") from None
if not isinstance(value, dict):
raise AppError("oauth_response_invalid")
return value
def _request(session, method, url, **kwargs):
if url not in {DISCOVERY_URL, TOKEN_URL, JWKS_URL, MODELS_URL, RESPONSES_URL}:
raise AppError("endpoint_not_allowed")
kwargs.update(timeout=HTTP_TIMEOUT, allow_redirects=False)
try:
return session.request(method, url, **kwargs)
except requests.RequestException:
raise AppError("network_error") from None
def check_discovery(session):
data = _safe_response(_request(session, "GET", DISCOVERY_URL))
if (
data.get("issuer") != ISSUER
or data.get("authorization_endpoint") != AUTHORIZE_URL
or data.get("token_endpoint") != TOKEN_URL
or data.get("jwks_uri") != JWKS_URL
):
raise AppError("discovery_mismatch")
def fetch_jwks(session):
data = _safe_response(_request(session, "GET", JWKS_URL))
if not isinstance(data.get("keys"), list):
raise AppError("jwks_invalid")
return data
def validate_id_token(encoded, client_id, nonce, session, now=None):
try:
header = jwt.get_unverified_header(encoded)
except jwt.PyJWTError:
raise AppError("id_token_invalid") from None
kid = header.get("kid")
if header.get("alg") != "RS256" or not isinstance(kid, str) or not kid:
raise AppError("id_token_invalid")
try:
key_set = jwt.PyJWKSet.from_dict(fetch_jwks(session))
key = next(item.key for item in key_set.keys if item.key_id == kid)
claims = jwt.decode(
encoded,
key,
algorithms=["RS256"],
audience=client_id,
issuer=ISSUER,
options={"require": ["iss", "aud", "exp", "iat", "nonce", "sub"]},
leeway=0,
)
except (jwt.PyJWTError, StopIteration, ValueError, TypeError):
raise AppError("id_token_invalid") from None
if now is not None and claims.get("exp", 0) <= now:
raise AppError("id_token_invalid")
if not hmac.compare_digest(str(claims["nonce"]), nonce):
raise AppError("id_token_invalid")
if not isinstance(claims["sub"], str) or not claims["sub"]:
raise AppError("id_token_invalid")
return claims
def validate_token_response(data):
required = ("access_token", "refresh_token", "id_token", "scope")
if any(not isinstance(data.get(field), str) or not data[field] for field in required):
raise AppError("token_response_invalid")
if data.get("token_type") != "Bearer" or isinstance(data.get("expires_in"), bool):
raise AppError("token_response_invalid")
if not isinstance(data.get("expires_in"), int) or data["expires_in"] <= 0:
raise AppError("token_response_invalid")
scopes = sorted(set(data["scope"].split()))
if REQUIRED_SCOPE not in scopes:
raise AppError("scope_missing")
return scopes
class CallbackAttempt:
def __init__(self, state, client_id, deadline):
self.state = state
self.client_id = client_id
self.deadline = deadline
self.result = None
self.consumed = False
self.lock = threading.Lock()
def process(self, raw_query, host, expected_host, now=None):
now = time.monotonic() if now is None else now
if len(raw_query) > MAX_CALLBACK or host != expected_host or now > self.deadline:
raise AppError("callback_invalid")
try:
values = parse_qs(raw_query, keep_blank_values=True, strict_parsing=True)
except ValueError:
raise AppError("callback_invalid") from None
allowed = {"state", "code", "scope", "client_id", "error", "error_description"}
if not values or set(values) - allowed or any(len(items) != 1 for items in values.values()):
raise AppError("callback_invalid")
if any(len(items[0]) > 4096 for items in values.values()):
raise AppError("callback_invalid")
returned_state = values.get("state", [""])[0]
if not hmac.compare_digest(returned_state, self.state):
raise AppError("state_mismatch")
with self.lock:
if self.consumed:
raise AppError("callback_replayed")
if "error" in values:
if "code" in values or not values["error"][0]:
raise AppError("callback_invalid")
self.consumed = True
self.result = {"denied": True}
return self.result
code = values.get("code", [""])[0]
if not code:
raise AppError("callback_invalid")
supplied = values.get("client_id", [None])[0]
if self.client_id == DYNAMIC_CLIENT:
if not supplied or supplied == DYNAMIC_CLIENT or not CLIENT_RE.fullmatch(supplied):
raise AppError("client_id_invalid")
issued = supplied
else:
if supplied is not None and supplied != self.client_id:
raise AppError("client_id_mismatch")
issued = self.client_id
self.consumed = True
self.result = {"denied": False, "code": code, "client_id": issued}
return self.result
class LoopbackHTTPServer(ThreadingMixIn, HTTPServer):
daemon_threads = True
block_on_close = False
def handle_error(self, request, client_address):
return
def get_request(self):
request, address = super().get_request()
request.settimeout(SOCKET_TIMEOUT)
return request, address
def callback_handler(attempt, expected_host):
class Handler(BaseHTTPRequestHandler):
def log_message(self, format, *args):
return
def _reply(self, status, text):
body = (text + "\n").encode("utf-8")
try:
self.send_response(status)
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.send_header("Referrer-Policy", "no-referrer")
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
except OSError:
return
def do_GET(self):
split = urlsplit(self.path)
if split.path != "/auth/callback" or split.fragment or len(self.path) > MAX_CALLBACK:
self._reply(404, "Not found")
return
try:
result = attempt.process(split.query, self.headers.get("Host", ""), expected_host)
except AppError:
self._reply(400, "Invalid callback. Return to the terminal and retry if needed.")
return
if result["denied"]:
self._reply(200, "Authorization declined. You may close this page.")
else:
self._reply(200, "Authorization received. You may close this page.")
return Handler
def credentials_path(state_dir):
return secure_dir(state_dir) / "credentials.json"
def credentials_valid(value):
strings = (
"issuer",
"subject",
"client_id",
"host_id",
"access_token",
"refresh_token",
"id_token",
"token_type",
"saved_at",
)
return bool(
isinstance(value, dict)
and all(isinstance(value.get(field), str) and value[field] for field in strings)
and value["issuer"] == ISSUER
and value["token_type"] == "Bearer"
and isinstance(value.get("scopes"), list)
and REQUIRED_SCOPE in value["scopes"]
and not isinstance(value.get("expires_at"), bool)
and isinstance(value.get("expires_at"), (int, float))
)
def read_credentials(directory):
value = read_json(credentials_path(directory))
if value is not None and not credentials_valid(value):
raise AppError("invalid_state")
return value
@contextlib.contextmanager
def credential_lock(state_dir):
directory = secure_dir(state_dir)
lock_path = directory / "credentials.lock"
_regular_nofollow(lock_path)
descriptor = os.open(lock_path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
try:
os.fchmod(descriptor, 0o600)
fcntl.flock(descriptor, fcntl.LOCK_EX)
yield directory
finally:
os.close(descriptor)
def exchange_code(session, code, verifier, redirect_uri, client_id):
response = _request(
session,
"POST",
TOKEN_URL,
data={
"grant_type": "authorization_code",
"client_id": client_id,
"code": code,
"code_verifier": verifier,
"redirect_uri": redirect_uri,
"resource": RESOURCE,
},
)
return _safe_response(response)
def login(args, session=None):
session = session or new_session()
with credential_lock(args.state_dir) as directory:
host = host_id(directory, args.host_id_file)
old = read_credentials(directory)
requested_client = old["client_id"] if old else DYNAMIC_CLIENT
verifier = secrets.token_urlsafe(64)
state = secrets.token_urlsafe(32)
nonce = secrets.token_urlsafe(32)
server = LoopbackHTTPServer(("127.0.0.1", args.port), BaseHTTPRequestHandler)
port = server.server_address[1]
expected_host = f"127.0.0.1:{port}"
redirect_uri = f"http://{expected_host}/auth/callback"
attempt = CallbackAttempt(state, requested_client, time.monotonic() + args.timeout)
server.RequestHandlerClass = callback_handler(attempt, expected_host)
server.timeout = min(1, args.timeout)
query = {
"client_id": requested_client,
"ext_agent_host_id": host,
"response_type": "code",
"redirect_uri": redirect_uri,
"scope": SCOPES,
"resource": RESOURCE,
"state": state,
"nonce": nonce,
"code_challenge_method": "S256",
"code_challenge": pkce_challenge(verifier),
}
if requested_client == DYNAMIC_CLIENT:
query["agent_name_hint"] = AGENT_NAME
print(AUTHORIZE_URL + "?" + urlencode(query), flush=True)
try:
while attempt.result is None and time.monotonic() <= attempt.deadline:
server.handle_request()
finally:
server.server_close()
if attempt.result is None:
raise AppError("callback_timeout")
if attempt.result["denied"]:
raise AppError("authorization_denied")
check_discovery(session)
issued = attempt.result["client_id"]
token = exchange_code(session, attempt.result["code"], verifier, redirect_uri, issued)
scopes = validate_token_response(token)
claims = validate_id_token(token["id_token"], issued, nonce, session)
if old and old["subject"] != claims["sub"]:
raise AppError("account_mismatch")
now = time.time()
saved = {
"issuer": ISSUER,
"subject": claims["sub"],
"client_id": issued,
"host_id": host,
"access_token": token["access_token"],
"refresh_token": token["refresh_token"],
"id_token": token["id_token"],
"token_type": "Bearer",
"scopes": scopes,
"saved_at": utc_now(),
"expires_at": now + token["expires_in"],
}
atomic_json(credentials_path(directory), saved)
print(json.dumps({"authorized": True}))
def status(args):
directory = secure_dir(args.state_dir)
host_data = read_json(directory / "host.json")
if host_data is not None and (
not isinstance(host_data, dict) or not isinstance(host_data.get("host_id"), str)
):
raise AppError("invalid_state")
creds = read_credentials(directory)
authorized = credentials_valid(creds)
result = {
"authorized": authorized,
"access_token_expired": not isinstance(creds, dict)
or not isinstance(creds.get("expires_at"), (int, float))
or creds.get("expires_at", 0) <= time.time(),
}
if host_data and isinstance(host_data.get("host_id"), str):
result["host_id"] = host_data["host_id"]
print(json.dumps(result, sort_keys=True))
def refresh(session, path, creds):
response = _request(
session,
"POST",
TOKEN_URL,
data={
"grant_type": "refresh_token",
"client_id": creds["client_id"],
"refresh_token": creds["refresh_token"],
"resource": RESOURCE,
},
)
data = _safe_response(response)
scopes = validate_token_response({**data, "id_token": data.get("id_token", creds.get("id_token"))})
if data["refresh_token"] == creds["refresh_token"]:
raise AppError("refresh_not_rotated")
updated = dict(creds)
updated.update(
access_token=data["access_token"],
refresh_token=data["refresh_token"],
token_type="Bearer",
scopes=scopes,
saved_at=utc_now(),
expires_at=time.time() + data["expires_in"],
)
atomic_json(path, updated)
return updated
def models(args, session=None):
session = session or new_session()
with credential_lock(args.state_dir) as directory:
path = credentials_path(directory)
creds = read_credentials(directory)
if not isinstance(creds, dict):
raise AppError("not_authorized")
if creds.get("expires_at", 0) <= time.time() + 120:
creds = refresh(session, path, creds)
response = _request(
session,
"GET",
MODELS_URL,
headers={"Authorization": "Bearer " + creds["access_token"]},
)
data = _safe_response(response)
entries = data.get("models")
if not isinstance(entries, list):
raise AppError("models_response_invalid")
visible = []
for item in entries:
if (
isinstance(item, dict)
and item.get("visibility") == "list"
and isinstance(item.get("slug"), str)
and isinstance(item.get("display_name"), str)
):
visible.append({"slug": item["slug"], "display_name": item["display_name"]})
print(json.dumps(visible, separators=(",", ":")))
def parser():
result = argparse.ArgumentParser(prog="affine-chatgpt")
result.add_argument("--state-dir", type=Path, default=default_state_dir())
commands = result.add_subparsers(dest="command", required=True)
login_parser = commands.add_parser("login")
login_parser.add_argument("--port", type=int, default=1455)
login_parser.add_argument("--timeout", type=int, default=900)
login_parser.add_argument("--host-id-file", type=Path)
commands.add_parser("status")
commands.add_parser("models")
serve_parser = commands.add_parser("serve")
serve_parser.add_argument("--host", default="127.0.0.1")
serve_parser.add_argument("--port", type=int, default=3012)
serve_parser.add_argument("--gateway-key-file", type=Path, required=True)
return result
def main(argv=None):
args = parser().parse_args(argv)
try:
if args.command == "login":
if not 0 <= args.port <= 65535 or args.timeout <= 0:
raise AppError("invalid_argument")
login(args)
elif args.command == "status":
status(args)
elif args.command == "models":
models(args)
else:
if not 0 <= args.port <= 65535:
raise AppError("invalid_argument")
try:
ipaddress.ip_address(args.host)
except ValueError:
raise AppError("invalid_argument") from None
from affine_gateway import serve
serve(args)
except AppError as error:
print(f"error: {error}", file=sys.stderr)
return 1
except OSError:
print("error: local_io_error", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,612 @@
"""Minimal OpenAI Responses-compatible gateway for AFFiNE."""
import hmac
import json
import os
import re
import socket
import stat
import threading
import time
from typing import cast
from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
from urllib.parse import urlsplit
import requests
import affine_chatgpt as auth
MAX_BODY = 2 * 1024 * 1024
MAX_EVENT = 8 * 1024 * 1024
CONNECT_TIMEOUT = 15
READ_TIMEOUT = 90
SOCKET_TIMEOUT = 95
HEADER_TIMEOUT = 10
CATALOG_TTL = 300
MAX_CONCURRENT = 16
MAX_CONNECTIONS = 32
NAMESPACE = "affine"
NAME_RE = re.compile(r"^[A-Za-z0-9_.-]{1,128}$")
NAMESPACE_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
SAFE_UPSTREAM_CODES = {
"invalid_request_error",
"model_not_found",
"rate_limit_exceeded",
"server_error",
"insufficient_quota",
}
IGNORED_FIELDS = {
"max_output_tokens",
"max_tool_calls",
"metadata",
"moderation",
"multi_agent",
"prompt_cache_retention",
"safety_identifier",
"temperature",
"top_logprobs",
"top_p",
"truncation",
"user",
}
REJECTED_FIELDS = {"background", "conversation", "previous_response_id", "prompt"}
class GatewayError(Exception):
"""Expected client/upstream failure safe for public output."""
def __init__(self, status, code):
super().__init__(code)
self.status = status
self.code = code
def read_gateway_key(path):
try:
info = path.lstat()
except OSError:
raise auth.AppError("invalid_gateway_key") from None
if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077:
raise auth.AppError("invalid_gateway_key")
try:
descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
with os.fdopen(descriptor, "r", encoding="utf-8") as stream:
value = stream.read(4097).strip()
except (OSError, UnicodeError):
raise auth.AppError("invalid_gateway_key") from None
if len(value) < 32 or len(value) > 4096 or "\n" in value or "\r" in value:
raise auth.AppError("invalid_gateway_key")
return value
def new_session():
session = requests.Session()
session.trust_env = False
return session
def _response_json(response, code):
if response.is_redirect:
raise GatewayError(response.status_code, "upstream_redirect")
try:
value = response.json()
except (requests.RequestException, ValueError):
raise GatewayError(502, code) from None
if not isinstance(value, dict):
raise GatewayError(502, code)
return value
class Provider:
def __init__(self, state_dir, session=None, now=time.time):
self.state_dir = state_dir
self.session = session or new_session()
self.now = now
self.catalog = None
self.catalog_at = 0
self.lock = threading.Lock()
def credentials(self):
with auth.credential_lock(self.state_dir) as directory:
path = auth.credentials_path(directory)
creds = auth.read_credentials(directory)
if not isinstance(creds, dict):
raise auth.AppError("not_authorized")
if creds.get("expires_at", 0) <= self.now() + 120:
creds = auth.refresh(self.session, path, creds)
return creds
def ready(self):
self.credentials()
def models(self):
with self.lock:
if self.catalog is not None and self.now() - self.catalog_at < CATALOG_TTL:
return list(self.catalog)
creds = self.credentials()
response = auth._request(
self.session,
"GET",
auth.MODELS_URL,
headers={"Authorization": "Bearer " + creds["access_token"]},
)
if response.is_redirect or response.status_code != 200:
raise GatewayError(response.status_code, "upstream_models_error")
data = _response_json(response, "upstream_models_invalid")
entries = data.get("models")
if not isinstance(entries, list):
raise GatewayError(502, "upstream_models_invalid")
catalog = []
for item in entries:
if (
isinstance(item, dict)
and item.get("visibility") == "list"
and isinstance(item.get("slug"), str)
and item["slug"]
and isinstance(item.get("display_name"), str)
):
catalog.append((item["slug"], item["display_name"]))
self.catalog = catalog
self.catalog_at = self.now()
return list(catalog)
def response(self, body):
if auth.RESPONSES_URL != "https://api.openai.com/v1/responses":
raise GatewayError(500, "endpoint_not_allowed")
creds = self.credentials()
try:
return self.session.request(
"POST",
auth.RESPONSES_URL,
headers={
"Authorization": "Bearer " + creds["access_token"],
"Content-Type": "application/json",
"Accept": "text/event-stream",
},
json=body,
stream=True,
timeout=(CONNECT_TIMEOUT, READ_TIMEOUT),
allow_redirects=False,
)
except requests.RequestException:
raise GatewayError(502, "upstream_network_error") from None
def _copy_keys(value, allowed):
return {key: value[key] for key in allowed if key in value}
def _normalize_content(content, role):
if isinstance(content, str):
return [{"type": "output_text" if role == "assistant" else "input_text", "text": content}]
if not isinstance(content, list) or not content:
raise GatewayError(400, "invalid_input")
result = []
for part in content:
if not isinstance(part, dict) or part.get("type") not in {"input_text", "output_text"}:
raise GatewayError(400, "unsupported_media")
if not isinstance(part.get("text"), str):
raise GatewayError(400, "invalid_input")
result.append({"type": part["type"], "text": part["text"]})
return result
def _normalize_item(item):
if not isinstance(item, dict):
raise GatewayError(400, "invalid_input")
item_type = item.get("type")
if item_type in (None, "message"):
role = item.get("role")
if role == "system":
role = "developer"
if role not in {"user", "assistant", "developer"}:
raise GatewayError(400, "invalid_input")
return {
"type": "message",
"role": role,
"content": _normalize_content(item.get("content"), role),
}
if item_type == "function_call":
result = _copy_keys(item, {"id", "call_id", "name", "arguments", "namespace", "status"})
if not all(isinstance(result.get(key), str) and result[key] for key in ("call_id", "name", "arguments")):
raise GatewayError(400, "invalid_input")
result["type"] = item_type
return result
if item_type == "function_call_output":
result = _copy_keys(item, {"id", "call_id", "output", "status"})
if not isinstance(result.get("call_id"), str) or not result["call_id"] or not isinstance(result.get("output"), str):
raise GatewayError(400, "invalid_input")
result["type"] = item_type
return result
if item_type == "reasoning":
result = _copy_keys(item, {"id", "summary", "content", "encrypted_content", "status"})
if not any(key in result for key in ("summary", "content", "encrypted_content")):
raise GatewayError(400, "invalid_input")
result["type"] = item_type
return result
raise GatewayError(400, "unsupported_input_type")
def _normalize_inner_tool(tool):
if not isinstance(tool, dict) or tool.get("type") not in {"function", "custom"}:
raise GatewayError(400, "unsupported_tool")
name = tool.get("name")
if not isinstance(name, str) or not NAME_RE.fullmatch(name):
raise GatewayError(400, "invalid_tool")
if tool["type"] == "function":
allowed = {"type", "name", "description", "parameters", "strict"}
else:
allowed = {"type", "name", "description", "format"}
if set(tool) - allowed:
raise GatewayError(400, "unsupported_tool_field")
return _copy_keys(tool, allowed)
def _normalize_tools(tools):
if not isinstance(tools, list) or not tools:
raise GatewayError(400, "invalid_tools")
if all(isinstance(tool, dict) and tool.get("type") in {"function", "custom"} for tool in tools):
return [{
"type": "namespace",
"name": NAMESPACE,
"description": "Functions provided and executed by AFFiNE.",
"tools": [_normalize_inner_tool(tool) for tool in tools],
}]
result = []
for namespace in tools:
if not isinstance(namespace, dict) or set(namespace) - {"type", "name", "description", "tools"}:
raise GatewayError(400, "unsupported_tool")
name = namespace.get("name")
nested = namespace.get("tools")
if namespace.get("type") != "namespace" or not isinstance(name, str) or not NAMESPACE_RE.fullmatch(name):
raise GatewayError(400, "unsupported_tool")
if not isinstance(namespace.get("description"), str) or not isinstance(nested, list) or not nested:
raise GatewayError(400, "invalid_tools")
result.append({
"type": "namespace",
"name": name,
"description": namespace["description"],
"tools": [_normalize_inner_tool(tool) for tool in nested],
})
return result
def _normalize_choice(choice, had_flat_tools):
if isinstance(choice, str) and choice in {"auto", "none", "required"}:
return choice
if not isinstance(choice, dict):
raise GatewayError(400, "unsupported_tool_choice")
result = dict(choice)
if result.get("type") in {"function", "custom"} and had_flat_tools:
if set(result) - {"type", "name"} or not isinstance(result.get("name"), str):
raise GatewayError(400, "unsupported_tool_choice")
result["namespace"] = NAMESPACE
return result
if result.get("type") in {"function", "custom"}:
if set(result) - {"type", "name", "namespace"}:
raise GatewayError(400, "unsupported_tool_choice")
return result
raise GatewayError(400, "unsupported_tool_choice")
def normalize_request(value, eligible):
if not isinstance(value, dict):
raise GatewayError(400, "invalid_json")
allowed = {"model", "input", "instructions", "tools", "tool_choice", "store", "stream"}
unknown = set(value) - allowed - IGNORED_FIELDS - REJECTED_FIELDS
if set(value) & REJECTED_FIELDS:
raise GatewayError(400, "unsupported_parameter")
if unknown:
raise GatewayError(400, "unsupported_parameter")
if "stream" in value and not isinstance(value["stream"], bool):
raise GatewayError(400, "invalid_stream")
if "store" in value and not isinstance(value["store"], bool):
raise GatewayError(400, "invalid_store")
model = value.get("model")
if not isinstance(model, str) or model not in eligible:
raise GatewayError(400, "model_not_available")
incoming = value.get("input")
if not isinstance(incoming, list) or not incoming:
raise GatewayError(400, "invalid_input")
result = {
"model": model,
"input": [_normalize_item(item) for item in incoming],
"store": False,
"stream": True,
}
if "instructions" in value:
if not isinstance(value["instructions"], str):
raise GatewayError(400, "invalid_instructions")
result["instructions"] = value["instructions"]
if "tools" in value:
flat = all(isinstance(tool, dict) and tool.get("type") in {"function", "custom"} for tool in value["tools"]) if isinstance(value["tools"], list) else False
result["tools"] = _normalize_tools(value["tools"])
if "tool_choice" in value:
result["tool_choice"] = _normalize_choice(value["tool_choice"], flat)
elif "tool_choice" in value:
raise GatewayError(400, "unsupported_tool_choice")
return result
def _events(response):
buffer = b""
try:
for chunk in response.iter_content(chunk_size=16384):
if not chunk:
continue
buffer += chunk
if len(buffer) > MAX_EVENT:
raise GatewayError(502, "upstream_stream_invalid")
while True:
positions = [(buffer.find(b"\n\n"), 2), (buffer.find(b"\r\n\r\n"), 4)]
positions = [(position, size) for position, size in positions if position >= 0]
if not positions:
break
position, size = min(positions)
raw, buffer = buffer[: position + size], buffer[position + size :]
yield raw, _event_data(raw)
if buffer.strip():
raise GatewayError(502, "upstream_stream_interrupted")
except requests.RequestException:
raise GatewayError(502, "upstream_stream_interrupted") from None
def _event_data(raw):
data = []
for line in raw.replace(b"\r\n", b"\n").split(b"\n"):
if line.startswith(b"data:"):
data.append(line[5:].lstrip())
if not data or b"\n".join(data) == b"[DONE]":
return None
try:
value = json.loads(b"\n".join(data))
except (ValueError, UnicodeError):
raise GatewayError(502, "upstream_stream_invalid") from None
if not isinstance(value, dict) or not isinstance(value.get("type"), str):
raise GatewayError(502, "upstream_stream_invalid")
return value
def _upstream_error(response):
code = "upstream_http_error"
try:
value = response.json()
candidate = value.get("error", {}).get("code")
if candidate in SAFE_UPSTREAM_CODES:
code = candidate
except (requests.RequestException, ValueError, AttributeError):
return GatewayError(response.status_code, code)
return GatewayError(response.status_code, code)
class GatewayServer(ThreadingMixIn, HTTPServer):
daemon_threads = True
block_on_close = False
def __init__(
self,
address,
provider,
key,
max_concurrent=MAX_CONCURRENT,
max_connections=MAX_CONNECTIONS,
):
self.provider = provider
self.gateway_key = key
self.capacity = threading.BoundedSemaphore(max_concurrent)
self.connection_capacity = threading.BoundedSemaphore(max_connections)
super().__init__(address, GatewayHandler)
def get_request(self):
request, address = super().get_request()
request.settimeout(HEADER_TIMEOUT)
return request, address
def process_request(self, request, client_address):
if not self.connection_capacity.acquire(blocking=False):
self.shutdown_request(request)
return
try:
super().process_request(request, client_address)
except BaseException:
self.connection_capacity.release()
raise
def process_request_thread(self, request, client_address):
try:
super().process_request_thread(request, client_address)
finally:
self.connection_capacity.release()
def handle_error(self, request, client_address):
return
class GatewayHandler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, format, *args):
return
@property
def gateway(self):
return cast(GatewayServer, self.server)
def _authorized(self):
value = self.headers.get("Authorization", "")
prefix = "Bearer "
supplied = value[len(prefix) :] if value.startswith(prefix) else ""
return hmac.compare_digest(supplied.encode(), self.gateway.gateway_key.encode())
def _json(self, status, value):
body = json.dumps(value, separators=(",", ":")).encode()
try:
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Cache-Control", "no-store")
self.send_header("Connection", "close")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
self.close_connection = True
except OSError:
return
def _error(self, error):
self.close_connection = True
self._json(error.status, {"error": {"message": "Gateway request failed.", "type": "gateway_error", "code": error.code}})
def _enter(self):
if not self.gateway.capacity.acquire(blocking=False):
self._error(GatewayError(503, "gateway_busy"))
return False
return True
def do_GET(self):
self.connection.settimeout(SOCKET_TIMEOUT)
if not self._enter():
return
try:
target = urlsplit(self.path)
if target.query or target.fragment:
self._error(GatewayError(404, "not_found"))
return
path = target.path
if path == "/healthz":
self._json(200, {"status": "ready"})
return
if not self._authorized():
self._error(GatewayError(401, "unauthorized"))
return
if path != "/v1/models":
self._error(GatewayError(404, "not_found"))
return
data = [{"id": slug, "object": "model", "created": 0, "owned_by": "openai"} for slug, _name in self.gateway.provider.models()]
self._json(200, {"object": "list", "data": data})
except GatewayError as error:
self._error(error)
except (auth.AppError, OSError):
self._error(GatewayError(503, "credentials_unavailable"))
finally:
self.gateway.capacity.release()
def do_POST(self):
self.connection.settimeout(SOCKET_TIMEOUT)
if not self._enter():
return
upstream = None
try:
if not self._authorized():
raise GatewayError(401, "unauthorized")
target = urlsplit(self.path)
if target.path != "/v1/responses" or target.query or target.fragment:
raise GatewayError(404, "not_found")
if self.headers.get("Transfer-Encoding") is not None:
raise GatewayError(400, "unsupported_transfer_encoding")
content_type = self.headers.get("Content-Type", "").lower().replace(" ", "")
if content_type not in {"application/json", "application/json;charset=utf-8"}:
raise GatewayError(415, "unsupported_content_type")
lengths = self.headers.get_all("Content-Length", [])
if len(lengths) != 1:
raise GatewayError(400, "invalid_content_length")
raw_length = lengths[0]
try:
length = int(raw_length) if raw_length is not None else -1
except ValueError:
length = -1
if length < 0:
raise GatewayError(411, "content_length_required")
if length > MAX_BODY:
raise GatewayError(413, "request_too_large")
try:
value = json.loads(self.rfile.read(length))
except (ValueError, UnicodeError):
raise GatewayError(400, "invalid_json") from None
eligible = {slug for slug, _name in self.gateway.provider.models()}
body = normalize_request(value, eligible)
wants_stream = value.get("stream") is True
upstream = self.gateway.provider.response(body)
if upstream.is_redirect or upstream.status_code != 200:
raise _upstream_error(upstream)
media_type = upstream.headers.get("Content-Type", "").split(";", 1)[0].strip().lower()
if media_type and media_type != "text/event-stream":
raise GatewayError(502, "upstream_content_type_invalid")
if wants_stream:
self._stream(upstream)
else:
self._aggregate(upstream)
except GatewayError as error:
self._error(error)
except (auth.AppError, OSError):
self._error(GatewayError(503, "credentials_unavailable"))
finally:
if upstream is not None:
upstream.close()
self.gateway.capacity.release()
def _stream(self, upstream):
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Cache-Control", "no-store")
self.send_header("Connection", "close")
self.end_headers()
terminal = False
try:
for raw, event in _events(upstream):
self.wfile.write(raw)
self.wfile.flush()
if event and event["type"] in {"response.completed", "response.failed", "response.incomplete", "error"}:
terminal = True
if not terminal:
raise GatewayError(502, "upstream_stream_interrupted")
except (GatewayError, OSError):
if not terminal:
safe = b'event: error\ndata: {"type":"error","code":"upstream_stream_interrupted","message":"Gateway stream interrupted."}\n\n'
try:
self.wfile.write(safe)
self.wfile.flush()
except OSError:
return
finally:
self.close_connection = True
def _aggregate(self, upstream):
completed = None
terminal_error = None
output_items = {}
for _raw, event in _events(upstream):
if event is None:
continue
if event["type"] == "response.output_item.done":
index = event.get("output_index")
item = event.get("item")
if isinstance(index, int) and not isinstance(index, bool) and 0 <= index < 1024 and isinstance(item, dict):
output_items[index] = item
else:
terminal_error = "upstream_response_invalid"
elif event["type"] == "response.completed":
response = event.get("response")
if isinstance(response, dict) and response.get("status") == "completed" and isinstance(response.get("output"), list):
completed = response
else:
terminal_error = "upstream_response_invalid"
elif event["type"] in {"response.failed", "response.incomplete", "error"}:
terminal_error = "upstream_response_failed"
if terminal_error or completed is None:
raise GatewayError(502, terminal_error or "upstream_stream_interrupted")
if not completed["output"] and output_items:
completed = {**completed, "output": [output_items[index] for index in sorted(output_items)]}
self._json(200, completed)
def serve(args):
key = read_gateway_key(args.gateway_key_file)
provider = Provider(args.state_dir)
provider.ready()
server = GatewayServer((args.host, args.port), provider, key)
try:
server.serve_forever(poll_interval=0.25)
finally:
server.server_close()
@@ -0,0 +1,706 @@
import io
import http.client
import json
import os
import socket
import stat
import tempfile
import threading
import time
import unittest
from contextlib import redirect_stderr, redirect_stdout
from pathlib import Path
from types import SimpleNamespace
from unittest import mock
from urllib.parse import parse_qs, urlencode, urlsplit
import jwt
import requests
from cryptography.hazmat.primitives.asymmetric import rsa
import affine_chatgpt as app
class Response:
def __init__(self, data=None, status=200, redirect=False):
self.data = data
self.status_code = status
self.is_redirect = redirect
def json(self):
if isinstance(self.data, Exception):
raise self.data
return self.data
class Session:
def __init__(self, responses=()):
self.trust_env = True
self.responses = list(responses)
self.calls = []
def request(self, method, url, **kwargs):
self.calls.append((method, url, kwargs))
result = self.responses.pop(0)
if isinstance(result, Exception):
raise result
return result
class ProviderSession:
def __init__(self, key, subject="account-subject"):
self.key = key
self.subject = subject
self.nonce = None
self.calls = []
def request(self, method, url, **kwargs):
self.calls.append((method, url, kwargs))
if url == app.DISCOVERY_URL:
return Response(
{
"issuer": app.ISSUER,
"authorization_endpoint": app.AUTHORIZE_URL,
"token_endpoint": app.TOKEN_URL,
"jwks_uri": app.JWKS_URL,
}
)
if url == app.TOKEN_URL:
now = int(time.time())
client_id = kwargs["data"]["client_id"]
identity = jwt.encode(
{
"iss": app.ISSUER,
"aud": client_id,
"exp": now + 300,
"iat": now,
"nonce": self.nonce,
"sub": self.subject,
},
self.key,
algorithm="RS256",
headers={"kid": "integration-key"},
)
return Response(
{
"access_token": "integration-access",
"refresh_token": "integration-refresh",
"id_token": identity,
"token_type": "Bearer",
"expires_in": 3600,
"scope": app.SCOPES,
}
)
if url == app.JWKS_URL:
return Response({"keys": [jwk_for(self.key, "integration-key")]})
raise AssertionError(f"unexpected provider URL: {url}")
def jwk_for(key, kid="test-key"):
numbers = key.public_key().public_numbers()
def encoded(number):
size = (number.bit_length() + 7) // 8
return app.base64.urlsafe_b64encode(number.to_bytes(size, "big")).rstrip(b"=").decode()
return {
"kty": "RSA",
"kid": kid,
"use": "sig",
"alg": "RS256",
"n": encoded(numbers.n),
"e": encoded(numbers.e),
}
class SecurityTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
self.state = Path(self.temporary.name) / "state"
def tearDown(self):
self.temporary.cleanup()
def test_pkce_is_deterministic_and_unpadded(self):
self.assertEqual(
app.pkce_challenge("verifier"),
"iMnq5o6zALKXGivsnlom_0F5_WYda32GHkxlV7mq7hQ",
)
self.assertNotIn("=", app.pkce_challenge("verifier"))
def test_login_default_session_ignores_proxy_environment(self):
session = Session()
args = SimpleNamespace(state_dir=self.state, host_id_file=None, port=0, timeout=0)
with mock.patch.object(app.requests, "Session", return_value=session):
with redirect_stdout(io.StringIO()):
with self.assertRaisesRegex(app.AppError, "callback_timeout"):
app.login(args)
self.assertFalse(session.trust_env)
def test_atomic_permissions_and_symlink_protection(self):
path = self.state / "credentials.json"
app.atomic_json(path, {"safe": True})
self.assertEqual(stat.S_IMODE(self.state.stat().st_mode), 0o700)
self.assertEqual(stat.S_IMODE(path.stat().st_mode), 0o600)
path.unlink()
target = Path(self.temporary.name) / "target"
target.write_text("unchanged", encoding="utf-8")
path.symlink_to(target)
with self.assertRaisesRegex(app.AppError, "unsafe_state_file"):
app.atomic_json(path, {"unsafe": True})
self.assertEqual(target.read_text(encoding="utf-8"), "unchanged")
def test_state_directory_symlink_rejected(self):
real = Path(self.temporary.name) / "real"
real.mkdir()
self.state.symlink_to(real, target_is_directory=True)
with self.assertRaisesRegex(app.AppError, "unsafe_state_dir"):
app.secure_dir(self.state)
def test_atomic_write_syncs_file_and_parent_directory(self):
original_fsync = os.fsync
synced_directories = []
def record_fsync(descriptor):
synced_directories.append(stat.S_ISDIR(os.fstat(descriptor).st_mode))
original_fsync(descriptor)
with mock.patch.object(app.os, "fsync", side_effect=record_fsync):
app.atomic_json(self.state / "credentials.json", {"safe": True})
self.assertEqual(synced_directories, [False, True])
def test_insecure_existing_file_rejected(self):
self.state.mkdir(mode=0o700)
path = self.state / "credentials.json"
path.write_text("{}", encoding="utf-8")
path.chmod(0o644)
with self.assertRaisesRegex(app.AppError, "unsafe_state_file"):
app.read_json(path)
def test_status_exposes_only_allowed_fields(self):
app.atomic_json(self.state / "host.json", {"host_id": "urn:uuid:test"})
app.atomic_json(
self.state / "credentials.json",
{
"issuer": app.ISSUER,
"subject": "private-subject",
"client_id": "issued",
"host_id": "urn:uuid:test",
"access_token": "access-secret",
"refresh_token": "refresh-secret",
"id_token": "identity-secret",
"token_type": "Bearer",
"saved_at": "date",
"expires_at": time.time() + 60,
"scopes": [app.REQUIRED_SCOPE],
},
)
output = io.StringIO()
with redirect_stdout(output):
app.status(SimpleNamespace(state_dir=self.state))
result = json.loads(output.getvalue())
self.assertEqual(set(result), {"authorized", "access_token_expired", "host_id"})
self.assertTrue(result["authorized"])
self.assertNotIn("secret", output.getvalue())
self.assertNotIn("subject", output.getvalue())
def test_status_handles_malformed_json_shape(self):
app.atomic_json(self.state / "credentials.json", ["malformed"])
with self.assertRaisesRegex(app.AppError, "invalid_state"):
app.status(SimpleNamespace(state_dir=self.state))
def test_main_sanitizes_malformed_json_and_shape(self):
cases = ("{broken", '["wrong-shape"]')
for content in cases:
with self.subTest(content=content):
self.state.mkdir(mode=0o700, exist_ok=True)
path = self.state / "credentials.json"
path.write_text(content, encoding="utf-8")
path.chmod(0o600)
stderr = io.StringIO()
with redirect_stderr(stderr):
result = app.main(
["--state-dir", str(self.state), "login", "--port", "0", "--timeout", "1"]
)
self.assertEqual(result, 1)
self.assertEqual(stderr.getvalue(), "error: invalid_state\n")
def test_main_sanitizes_malformed_host_shape(self):
app.atomic_json(self.state / "host.json", ["wrong-shape"])
stderr = io.StringIO()
with redirect_stderr(stderr):
result = app.main(
["--state-dir", str(self.state), "login", "--port", "0", "--timeout", "1"]
)
self.assertEqual(result, 1)
self.assertEqual(stderr.getvalue(), "error: invalid_state\n")
def test_occupied_port_is_sanitized_local_io_error(self):
listener = socket.socket()
listener.bind(("127.0.0.1", 0))
listener.listen()
try:
port = listener.getsockname()[1]
stderr = io.StringIO()
with redirect_stderr(stderr):
result = app.main(
["--state-dir", str(self.state), "login", "--port", str(port), "--timeout", "1"]
)
self.assertEqual(result, 1)
self.assertEqual(stderr.getvalue(), "error: local_io_error\n")
finally:
listener.close()
class CallbackTests(unittest.TestCase):
def attempt(self, client=app.DYNAMIC_CLIENT):
return app.CallbackAttempt("expected-state", client, 100)
def test_state_nonce_mismatch_does_not_consume(self):
attempt = self.attempt()
with self.assertRaisesRegex(app.AppError, "state_mismatch"):
attempt.process("state=wrong&error=access_denied", "127.0.0.1:1455", "127.0.0.1:1455", 1)
self.assertFalse(attempt.consumed)
class LoopbackIntegrationTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
self.state = Path(self.temporary.name) / "state"
def tearDown(self):
self.temporary.cleanup()
def start_login(self, provider):
output = io.StringIO()
errors = io.StringIO()
failures = []
args = SimpleNamespace(
state_dir=self.state,
host_id_file=None,
port=0,
timeout=5,
)
def run():
try:
with mock.patch.object(app, "SOCKET_TIMEOUT", 0.1):
with redirect_stdout(output), redirect_stderr(errors):
app.login(args, provider)
except Exception as error:
failures.append(error)
thread = threading.Thread(target=run)
thread.start()
deadline = time.time() + 2
while "\n" not in output.getvalue() and time.time() < deadline:
time.sleep(0.01)
self.assertIn("\n", output.getvalue())
authorization = output.getvalue().splitlines()[0]
query = parse_qs(urlsplit(authorization).query)
provider.nonce = query["nonce"][0]
return thread, output, errors, failures, query
def callback(self, redirect_uri, parameters):
target = urlsplit(redirect_uri)
connection = http.client.HTTPConnection(target.hostname, target.port, timeout=2)
path = target.path + "?" + urlencode(parameters)
connection.request("GET", path, headers={"Host": f"127.0.0.1:{target.port}"})
response = connection.getresponse()
body = response.read()
connection.close()
return response.status, body
def test_real_listener_retries_malformed_callback_and_logs_nothing(self):
provider = ProviderSession(self.key)
thread, output, errors, failures, query = self.start_login(provider)
redirect_uri = query["redirect_uri"][0]
target = urlsplit(redirect_uri)
host, port = target.hostname, target.port
if not isinstance(host, str) or not isinstance(port, int):
self.fail("redirect URI did not contain loopback host and port")
stalled = socket.create_connection((host, port), timeout=1)
secret_code = "must-not-appear-in-http-log"
status, body = self.callback(
redirect_uri,
{"state": "wrong-state", "code": secret_code, "client_id": "issued-client"},
)
self.assertEqual(status, 400)
self.assertNotIn(secret_code.encode(), body)
status, body = self.callback(
redirect_uri,
{
"state": query["state"][0],
"code": "valid-code",
"client_id": "issued-client",
},
)
self.assertEqual(status, 200)
self.assertNotIn(b"valid-code", body)
stalled.close()
thread.join(3)
self.assertFalse(thread.is_alive())
self.assertEqual(failures, [])
self.assertEqual(errors.getvalue(), "")
self.assertNotIn(secret_code, output.getvalue())
saved = app.read_json(self.state / "credentials.json")
assert isinstance(saved, dict)
self.assertEqual(saved["subject"], "account-subject")
self.assertEqual(saved["client_id"], "issued-client")
token_call = next(call for call in provider.calls if call[1] == app.TOKEN_URL)
self.assertEqual(token_call[2]["data"]["code"], "valid-code")
def test_valid_rsa_failure_preserves_old_credentials(self):
host = "urn:uuid:00000000-0000-4000-8000-000000000000"
app.atomic_json(self.state / "host.json", {"host_id": host})
old = {
"issuer": app.ISSUER,
"subject": "old-subject",
"client_id": "issued-client",
"host_id": host,
"access_token": "old-access",
"refresh_token": "old-refresh",
"id_token": "old-identity",
"token_type": "Bearer",
"scopes": [app.REQUIRED_SCOPE],
"saved_at": "old-date",
"expires_at": time.time() + 60,
}
path = self.state / "credentials.json"
app.atomic_json(path, old)
before = path.read_bytes()
provider = ProviderSession(self.key, subject="different-subject")
thread, _output, errors, failures, query = self.start_login(provider)
status, _body = self.callback(
query["redirect_uri"][0],
{"state": query["state"][0], "code": "valid-code"},
)
self.assertEqual(status, 200)
thread.join(3)
self.assertFalse(thread.is_alive())
self.assertEqual(len(failures), 1)
self.assertIsInstance(failures[0], app.AppError)
self.assertEqual(str(failures[0]), "account_mismatch")
self.assertEqual(errors.getvalue(), "")
self.assertEqual(path.read_bytes(), before)
def test_disconnected_browser_does_not_abandon_valid_callback(self):
provider = ProviderSession(self.key)
thread, _output, errors, failures, query = self.start_login(provider)
target = urlsplit(query["redirect_uri"][0])
host, port = target.hostname, target.port
if not isinstance(host, str) or not isinstance(port, int):
self.fail("redirect URI did not contain loopback host and port")
path = target.path + "?" + urlencode(
{
"state": query["state"][0],
"code": "valid-code",
"client_id": "issued-client",
}
)
browser = socket.create_connection((host, port), timeout=1)
browser.sendall(
(
f"GET {path} HTTP/1.1\r\n"
f"Host: 127.0.0.1:{target.port}\r\n"
"Connection: close\r\n\r\n"
).encode("ascii")
)
browser.close()
thread.join(3)
self.assertFalse(thread.is_alive())
self.assertEqual(failures, [])
self.assertEqual(errors.getvalue(), "")
saved = app.read_json(self.state / "credentials.json")
assert isinstance(saved, dict)
self.assertEqual(saved["subject"], "account-subject")
class LockingTests(unittest.TestCase):
def attempt(self, client=app.DYNAMIC_CLIENT):
return app.CallbackAttempt("expected-state", client, 100)
def test_authorization_lock_serializes_concurrent_operation(self):
with tempfile.TemporaryDirectory() as temporary:
state = Path(temporary) / "state"
acquired = threading.Event()
release = threading.Event()
second_acquired = threading.Event()
def first():
with app.credential_lock(state):
acquired.set()
release.wait(2)
def second():
with app.credential_lock(state):
second_acquired.set()
first_thread = threading.Thread(target=first)
second_thread = threading.Thread(target=second)
first_thread.start()
self.assertTrue(acquired.wait(1))
second_thread.start()
self.assertFalse(second_acquired.wait(0.1))
release.set()
first_thread.join(1)
second_thread.join(1)
self.assertTrue(second_acquired.is_set())
def test_client_mismatch_and_valid_retry(self):
attempt = self.attempt("saved-client")
query = "state=expected-state&code=secret-code&client_id=other"
with self.assertRaisesRegex(app.AppError, "client_id_mismatch"):
attempt.process(query, "127.0.0.1:1455", "127.0.0.1:1455", 1)
result = attempt.process(
"state=expected-state&code=secret-code&client_id=saved-client",
"127.0.0.1:1455",
"127.0.0.1:1455",
1,
)
self.assertEqual(result["client_id"], "saved-client")
def test_dynamic_client_must_be_replaced(self):
for returned in ("", app.DYNAMIC_CLIENT, "bad client"):
attempt = self.attempt()
suffix = "" if not returned else "&client_id=" + returned.replace(" ", "+")
with self.assertRaisesRegex(app.AppError, "client_id_invalid"):
attempt.process(
"state=expected-state&code=code" + suffix,
"127.0.0.1:1455",
"127.0.0.1:1455",
1,
)
def test_replay_rejected(self):
attempt = self.attempt()
query = "state=expected-state&code=code&client_id=issued-client"
attempt.process(query, "127.0.0.1:1455", "127.0.0.1:1455", 1)
with self.assertRaisesRegex(app.AppError, "callback_replayed"):
attempt.process(query, "127.0.0.1:1455", "127.0.0.1:1455", 1)
def test_denial_is_terminal_and_nonsecret(self):
attempt = self.attempt()
result = attempt.process(
"state=expected-state&error=access_denied&error_description=private",
"127.0.0.1:1455",
"127.0.0.1:1455",
1,
)
self.assertEqual(result, {"denied": True})
self.assertNotIn("private", str(result))
def test_duplicate_and_unknown_query_fields_rejected(self):
bad_queries = (
"state=expected-state&state=expected-state&code=x&client_id=issued",
"state=expected-state&code=x&client_id=issued&extra=x",
)
for query in bad_queries:
with self.subTest(query=query):
with self.assertRaisesRegex(app.AppError, "callback_invalid"):
self.attempt().process(query, "127.0.0.1:1455", "127.0.0.1:1455", 1)
def test_host_and_expiry_rejected_without_consuming(self):
attempt = self.attempt()
query = "state=expected-state&code=x&client_id=issued"
with self.assertRaisesRegex(app.AppError, "callback_invalid"):
attempt.process(query, "localhost:1455", "127.0.0.1:1455", 1)
with self.assertRaisesRegex(app.AppError, "callback_invalid"):
attempt.process(query, "127.0.0.1:1455", "127.0.0.1:1455", 101)
self.assertFalse(attempt.consumed)
class TokenTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
cls.jwks = {"keys": [jwk_for(cls.key)]}
def token(self, **changes):
now = int(time.time())
claims = {
"iss": app.ISSUER,
"aud": "issued-client",
"exp": now + 300,
"iat": now,
"nonce": "expected-nonce",
"sub": "account-subject",
}
claims.update(changes)
return jwt.encode(claims, self.key, algorithm="RS256", headers={"kid": "test-key"})
def session(self):
return Session([Response(self.jwks)])
def test_rsa_signature_verification(self):
claims = app.validate_id_token(self.token(), "issued-client", "expected-nonce", self.session())
self.assertEqual(claims["sub"], "account-subject")
def test_wrong_issuer_audience_expiry_and_nonce_rejected(self):
cases = (
self.token(iss="https://evil.example"),
self.token(aud="wrong-client"),
self.token(exp=int(time.time()) - 1),
self.token(iat=int(time.time()) + 300),
self.token(nonce="wrong-nonce"),
)
for encoded in cases:
with self.subTest(encoded=encoded[-12:]):
with self.assertRaisesRegex(app.AppError, "id_token_invalid"):
app.validate_id_token(encoded, "issued-client", "expected-nonce", self.session())
def test_wrong_signature_and_untrusted_jku_rejected(self):
other = rsa.generate_private_key(public_exponent=65537, key_size=2048)
encoded = jwt.encode(
jwt.decode(self.token(), options={"verify_signature": False}),
other,
algorithm="RS256",
headers={"kid": "test-key", "jku": "https://evil.example/jwks"},
)
with self.assertRaisesRegex(app.AppError, "id_token_invalid"):
app.validate_id_token(encoded, "issued-client", "expected-nonce", self.session())
def test_missing_scope_rejected(self):
response = {
"access_token": "access",
"refresh_token": "refresh",
"id_token": "identity",
"token_type": "Bearer",
"expires_in": 3600,
"scope": "openid offline_access",
}
with self.assertRaisesRegex(app.AppError, "scope_missing"):
app.validate_token_response(response)
class NetworkAndModelsTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
self.state = Path(self.temporary.name) / "state"
self.path = self.state / "credentials.json"
self.creds = {
"issuer": app.ISSUER,
"subject": "subject",
"client_id": "issued-client",
"host_id": "urn:uuid:00000000-0000-4000-8000-000000000000",
"access_token": "old-access-secret",
"refresh_token": "old-refresh-secret",
"id_token": "old-id-token",
"token_type": "Bearer",
"scopes": [app.REQUIRED_SCOPE],
"saved_at": "date",
"expires_at": time.time() - 1,
}
app.atomic_json(self.path, self.creds)
def tearDown(self):
self.temporary.cleanup()
def test_models_default_session_ignores_proxy_environment(self):
credentials = {**self.creds, "expires_at": time.time() + 3600}
app.atomic_json(self.path, credentials)
session = Session([Response({"models": []})])
with mock.patch.object(app.requests, "Session", return_value=session):
with redirect_stdout(io.StringIO()):
app.models(SimpleNamespace(state_dir=self.state))
self.assertFalse(session.trust_env)
def test_refresh_rotation_and_models_visibility_filter(self):
refreshed = {
"access_token": "new-access-secret",
"refresh_token": "new-refresh-secret",
"token_type": "Bearer",
"expires_in": 3600,
"scope": app.REQUIRED_SCOPE + " openid",
}
catalog = {
"models": [
{"slug": "visible", "display_name": "Visible", "visibility": "list", "secret": "drop"},
{"slug": "hidden", "display_name": "Hidden", "visibility": "hide"},
{"slug": 1, "display_name": "Malformed", "visibility": "list"},
]
}
session = Session([Response(refreshed), Response(catalog)])
output = io.StringIO()
with redirect_stdout(output):
app.models(SimpleNamespace(state_dir=self.state), session)
self.assertEqual(json.loads(output.getvalue()), [{"slug": "visible", "display_name": "Visible"}])
saved = app.read_json(self.path)
assert isinstance(saved, dict)
self.assertEqual(saved["refresh_token"], "new-refresh-secret")
self.assertEqual(saved["id_token"], "old-id-token")
self.assertEqual(session.calls[1][2]["headers"]["Authorization"], "Bearer new-access-secret")
def test_refresh_failure_preserves_good_credentials(self):
before = self.path.read_bytes()
session = Session([Response({"error": "invalid_grant"}, status=400)])
with self.assertRaisesRegex(app.AppError, "oauth_http_error"):
app.models(SimpleNamespace(state_dir=self.state), session)
self.assertEqual(self.path.read_bytes(), before)
def test_malformed_credentials_fail_closed(self):
app.atomic_json(self.path, {"scopes": [app.REQUIRED_SCOPE], "expires_at": 0})
with self.assertRaisesRegex(app.AppError, "invalid_state"):
app.models(SimpleNamespace(state_dir=self.state), Session())
def test_unrotated_refresh_rejected_and_preserved(self):
before = self.path.read_bytes()
response = {
"access_token": "new-access",
"refresh_token": "old-refresh-secret",
"token_type": "Bearer",
"expires_in": 3600,
"scope": app.REQUIRED_SCOPE,
}
with self.assertRaisesRegex(app.AppError, "refresh_not_rotated"):
app.models(SimpleNamespace(state_dir=self.state), Session([Response(response)]))
self.assertEqual(self.path.read_bytes(), before)
def test_redirect_refused_for_credentials(self):
with self.assertRaisesRegex(app.AppError, "oauth_http_error"):
app.refresh(Session([Response({}, status=302, redirect=True)]), self.path, self.creds)
def test_lock_symlink_rejected_without_traceback(self):
target = Path(self.temporary.name) / "elsewhere"
target.write_text("safe", encoding="utf-8")
(self.state / "credentials.lock").symlink_to(target)
with self.assertRaisesRegex(app.AppError, "unsafe_state_file"):
app.models(SimpleNamespace(state_dir=self.state), Session())
def test_network_timeout_and_output_are_sanitized(self):
secret = "refresh-token-must-not-leak"
self.creds["refresh_token"] = secret
app.atomic_json(self.path, self.creds)
stderr = io.StringIO()
with mock.patch.object(app.requests, "Session", return_value=Session([requests.Timeout(secret)])):
with redirect_stderr(stderr):
result = app.main(["--state-dir", str(self.state), "models"])
self.assertEqual(result, 1)
self.assertEqual(stderr.getvalue(), "error: network_error\n")
self.assertNotIn(secret, stderr.getvalue())
def test_all_credential_requests_disable_redirects_and_have_timeout(self):
response = {
"access_token": "new-access",
"refresh_token": "new-refresh",
"token_type": "Bearer",
"expires_in": 3600,
"scope": app.REQUIRED_SCOPE,
}
session = Session([Response(response)])
app.refresh(session, self.path, self.creds)
kwargs = session.calls[0][2]
self.assertIs(kwargs["allow_redirects"], False)
self.assertEqual(kwargs["timeout"], app.HTTP_TIMEOUT)
self.assertNotIn("old-refresh-secret", str({k: v for k, v in kwargs.items() if k != "data"}))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,498 @@
import http.client
import json
import os
import socket
import subprocess
import sys
import tempfile
import threading
import time
import unittest
from pathlib import Path
from types import SimpleNamespace
from unittest import mock
import requests
import affine_chatgpt as auth
import affine_gateway as gateway
KEY = "gateway-test-key-0123456789abcdef"
MODEL = "gpt-5.6-luna"
def completed_response(output=None):
response = {
"id": "resp_test",
"object": "response",
"status": "completed",
"model": MODEL,
"output": output if output is not None else [{"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "ok"}]}],
"usage": {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2},
}
event = json.dumps({"type": "response.completed", "response": response}, separators=(",", ":"))
return response, ("event: response.completed\ndata: " + event + "\n\n").encode()
class FakeResponse:
def __init__(self, chunks=(), status=200, data=None, redirect=False, error=None, headers=None):
self.chunks = list(chunks)
self.status_code = status
self.data = data
self.is_redirect = redirect
self.error = error
self.headers = headers if headers is not None else {"Content-Type": "text/event-stream"}
self.closed = False
def iter_content(self, chunk_size=1):
for chunk in self.chunks:
if isinstance(chunk, Exception):
raise chunk
yield chunk
def json(self):
if isinstance(self.data, Exception):
raise self.data
return self.data
def close(self):
self.closed = True
class FakeProvider:
def __init__(self, responses=()):
self.responses = list(responses)
self.calls = []
def models(self):
self.calls.append("models")
return [(MODEL, "GPT 5.6 Luna")]
def response(self, body):
self.calls.append(("response", body))
return self.responses.pop(0)
class GatewayCase(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
def tearDown(self):
self.temporary.cleanup()
def valid(self, **changes):
value = {"model": MODEL, "input": [{"role": "user", "content": "hello"}]}
value.update(changes)
return value
class KeyAndNormalizationTests(GatewayCase):
def test_key_requires_owner_only_regular_nonempty_file(self):
path = Path(self.temporary.name) / "key"
path.write_text(KEY + "\n", encoding="utf-8")
path.chmod(0o600)
self.assertEqual(gateway.read_gateway_key(path), KEY)
path.chmod(0o640)
with self.assertRaisesRegex(auth.AppError, "invalid_gateway_key"):
gateway.read_gateway_key(path)
path.unlink()
target = Path(self.temporary.name) / "target"
target.write_text(KEY, encoding="utf-8")
path.symlink_to(target)
with self.assertRaisesRegex(auth.AppError, "invalid_gateway_key"):
gateway.read_gateway_key(path)
def test_serve_fails_before_listener_without_credentials(self):
path = Path(self.temporary.name) / "key"
path.write_text(KEY, encoding="utf-8")
path.chmod(0o600)
args = SimpleNamespace(
gateway_key_file=path,
state_dir=Path(self.temporary.name) / "state",
host="127.0.0.1",
port=0,
)
with self.assertRaisesRegex(auth.AppError, "not_authorized"):
gateway.serve(args)
def test_direct_script_sanitizes_gateway_startup_error(self):
path = Path(self.temporary.name) / "key"
path.write_text(KEY, encoding="utf-8")
path.chmod(0o600)
self.assertIsNotNone(auth.__file__)
script = Path(str(auth.__file__))
result = subprocess.run(
[
sys.executable,
str(script),
"--state-dir",
str(Path(self.temporary.name) / "state"),
"serve",
"--gateway-key-file",
str(path),
],
capture_output=True,
text=True,
timeout=5,
check=False,
)
self.assertEqual(result.returncode, 1)
self.assertEqual(result.stderr, "error: not_authorized\n")
self.assertNotIn("Traceback", result.stderr)
def test_normalization_forces_preview_contract_and_strips_sampling(self):
value = self.valid(
stream=False,
temperature=0.1,
max_output_tokens=20,
input=[{"role": "system", "content": [{"type": "input_text", "text": "rules"}]}],
)
result = gateway.normalize_request(value, {MODEL})
self.assertEqual(result["input"][0]["role"], "developer")
self.assertIs(result["store"], False)
self.assertIs(result["stream"], True)
self.assertNotIn("temperature", result)
self.assertNotIn("max_output_tokens", result)
def test_normalization_accepts_boolean_store_and_always_disables_it(self):
for incoming in (True, False):
with self.subTest(store=incoming):
result = gateway.normalize_request(self.valid(store=incoming), {MODEL})
self.assertIs(result["store"], False)
def test_flat_function_and_custom_tools_become_namespace(self):
tools = [
{"type": "function", "name": "artifactRead", "description": "Read", "parameters": {"type": "object"}},
{"type": "custom", "name": "artifactSearch", "format": {"type": "text"}},
]
result = gateway.normalize_request(
self.valid(tools=tools, tool_choice={"type": "function", "name": "artifactRead"}),
{MODEL},
)
namespace = result["tools"][0]
self.assertEqual(namespace["type"], "namespace")
self.assertEqual(namespace["name"], "affine")
self.assertEqual([tool["name"] for tool in namespace["tools"]], ["artifactRead", "artifactSearch"])
self.assertEqual(result["tool_choice"]["namespace"], "affine")
def test_nested_namespace_validates_function_custom_only(self):
tools = [{"type": "namespace", "name": "affine", "description": "AFFiNE", "tools": [{"type": "function", "name": "artifactRead"}]}]
self.assertEqual(gateway.normalize_request(self.valid(tools=tools), {MODEL})["tools"], tools)
tools[0]["tools"] = [{"type": "web_search"}]
with self.assertRaisesRegex(gateway.GatewayError, "unsupported_tool"):
gateway.normalize_request(self.valid(tools=tools), {MODEL})
def test_history_preserves_function_calls_outputs_and_reasoning_ciphertext(self):
history = [
{"type": "function_call", "id": "fc", "call_id": "call", "name": "artifactRead", "arguments": "{}", "namespace": "affine"},
{"type": "function_call_output", "call_id": "call", "output": "result"},
{"type": "reasoning", "id": "rs", "summary": [], "encrypted_content": "ciphertext"},
]
result = gateway.normalize_request(self.valid(input=history), {MODEL})
self.assertEqual(result["input"], history)
def test_rejects_unknown_model_media_tools_state_and_unknown_fields(self):
cases = [
(self.valid(model="fake-model"), "model_not_available"),
(self.valid(input=[{"role": "user", "content": [{"type": "input_image", "image_url": "x"}]}]), "unsupported_media"),
(self.valid(tools=[{"type": "code_interpreter"}]), "unsupported_tool"),
(self.valid(previous_response_id="resp"), "unsupported_parameter"),
(self.valid(secret_extension=True), "unsupported_parameter"),
(self.valid(stream="true"), "invalid_stream"),
(self.valid(store="false"), "invalid_store"),
]
for value, code in cases:
with self.subTest(code=code), self.assertRaisesRegex(gateway.GatewayError, code):
gateway.normalize_request(value, {MODEL})
def test_endpoint_allowlist_includes_only_official_response_url(self):
with self.assertRaisesRegex(auth.AppError, "endpoint_not_allowed"):
auth._request(mock.Mock(), "POST", "https://example.invalid/v1/responses")
self.assertEqual(auth.RESPONSES_URL, "https://api.openai.com/v1/responses")
class ProviderTests(GatewayCase):
def credentials(self, expires_at=None):
return {
"issuer": auth.ISSUER,
"subject": "subject",
"client_id": "client",
"host_id": "urn:uuid:00000000-0000-4000-8000-000000000000",
"access_token": "old-access-secret",
"refresh_token": "old-refresh-secret",
"id_token": "identity",
"token_type": "Bearer",
"saved_at": "date",
"expires_at": expires_at if expires_at is not None else time.time() + 3600,
"scopes": [auth.REQUIRED_SCOPE],
}
def test_new_session_ignores_proxy_environment(self):
self.assertIs(gateway.new_session().trust_env, False)
def test_catalog_filters_and_caches_visible_models(self):
response = FakeResponse(data={"models": [
{"slug": MODEL, "display_name": "Luna", "visibility": "list"},
{"slug": "hidden", "display_name": "Hidden", "visibility": "hide"},
]})
session = mock.Mock()
session.request.return_value = response
state = Path(self.temporary.name) / "state"
auth.atomic_json(state / "credentials.json", self.credentials())
provider = gateway.Provider(state, session=session)
self.assertEqual(provider.models(), [(MODEL, "Luna")])
self.assertEqual(provider.models(), [(MODEL, "Luna")])
self.assertEqual(session.request.call_count, 1)
kwargs = session.request.call_args.kwargs
self.assertIs(kwargs["allow_redirects"], False)
def test_refresh_rotation_under_lock_preserves_identity_token(self):
refreshed = FakeResponse(data={
"access_token": "new-access",
"refresh_token": "new-refresh",
"token_type": "Bearer",
"expires_in": 3600,
"scope": auth.REQUIRED_SCOPE,
})
session = mock.Mock()
session.request.return_value = refreshed
state = Path(self.temporary.name) / "state"
auth.atomic_json(state / "credentials.json", self.credentials(expires_at=0))
provider = gateway.Provider(state, session=session)
self.assertEqual(provider.credentials()["access_token"], "new-access")
saved = auth.read_json(state / "credentials.json")
assert isinstance(saved, dict)
self.assertEqual(saved["refresh_token"], "new-refresh")
self.assertEqual(saved["id_token"], "identity")
def test_response_transport_has_timeouts_no_redirects_and_sanitizes_network_error(self):
session = mock.Mock()
session.request.side_effect = requests.Timeout("access-secret-must-not-leak")
state = Path(self.temporary.name) / "state"
auth.atomic_json(state / "credentials.json", self.credentials())
provider = gateway.Provider(state, session=session)
with self.assertRaisesRegex(gateway.GatewayError, "upstream_network_error") as caught:
provider.response({"model": MODEL})
self.assertNotIn("secret", str(caught.exception))
kwargs = session.request.call_args.kwargs
self.assertEqual(kwargs["timeout"], (15, 90))
self.assertIs(kwargs["allow_redirects"], False)
self.assertIs(kwargs["stream"], True)
class LoopbackGatewayTests(GatewayCase):
def start_server(self, provider):
server = gateway.GatewayServer(("127.0.0.1", 0), provider, KEY)
thread = threading.Thread(target=server.serve_forever, kwargs={"poll_interval": 0.01})
thread.start()
self.addCleanup(server.server_close)
self.addCleanup(thread.join, 2)
self.addCleanup(server.shutdown)
return server
def request(self, server, method, path, body=None, headers=None):
connection = http.client.HTTPConnection("127.0.0.1", server.server_address[1], timeout=2)
encoded = None if body is None else json.dumps(body).encode()
actual = dict(headers or {})
if encoded is not None:
actual.setdefault("Content-Type", "application/json")
actual.setdefault("Content-Length", str(len(encoded)))
connection.request(method, path, body=encoded, headers=actual)
response = connection.getresponse()
data = response.read()
result = response.status, dict(response.getheaders()), data
connection.close()
return result
def authorized(self):
return {"Authorization": "Bearer " + KEY}
def test_unauthorized_request_does_not_parse_or_touch_provider(self):
provider = FakeProvider()
server = self.start_server(provider)
status, _headers, body = self.request(
server,
"POST",
"/v1/responses",
body=b"not-json".decode(),
headers={"Authorization": "Bearer wrong", "Content-Type": "text/plain"},
)
self.assertEqual(status, 401)
self.assertEqual(provider.calls, [])
self.assertNotIn(b"not-json", body)
def test_connections_are_bounded_before_header_parsing(self):
provider = FakeProvider()
server = gateway.GatewayServer(("127.0.0.1", 0), provider, KEY, max_connections=1)
thread = threading.Thread(target=server.serve_forever, kwargs={"poll_interval": 0.01})
thread.start()
first = socket.create_connection(("127.0.0.1", server.server_address[1]), timeout=2)
deadline = time.time() + 1
while time.time() < deadline:
if not server.connection_capacity.acquire(blocking=False):
break
server.connection_capacity.release()
time.sleep(0.01)
else:
self.fail("first connection was not admitted")
second = socket.create_connection(("127.0.0.1", server.server_address[1]), timeout=2)
second.settimeout(1)
second.sendall(b"GET /healthz HTTP/1.1\r\nHost: localhost\r\n\r\n")
self.assertEqual(second.recv(1), b"")
second.close()
first.close()
server.shutdown()
thread.join(2)
server.server_close()
def test_health_and_models_are_minimal_and_no_store(self):
provider = FakeProvider()
server = self.start_server(provider)
status, headers, body = self.request(server, "GET", "/healthz")
self.assertEqual((status, json.loads(body)), (200, {"status": "ready"}))
self.assertEqual(headers["Cache-Control"], "no-store")
status, _headers, body = self.request(server, "GET", "/v1/models", headers=self.authorized())
self.assertEqual(status, 200)
self.assertEqual(json.loads(body)["data"][0]["id"], MODEL)
def test_invalid_oversize_and_chunked_bodies_never_reach_provider(self):
provider = FakeProvider()
server = self.start_server(provider)
base = {**self.authorized(), "Content-Type": "text/plain"}
status, _headers, _body = self.request(server, "POST", "/v1/responses", {}, base)
self.assertEqual(status, 415)
raw = socket.create_connection(("127.0.0.1", server.server_address[1]), timeout=2)
raw.sendall((
"POST /v1/responses HTTP/1.1\r\nHost: localhost\r\n"
f"Authorization: Bearer {KEY}\r\nContent-Type: application/json\r\n"
"Transfer-Encoding: chunked\r\n\r\n2\r\n{}\r\n0\r\n\r\n"
).encode())
self.assertIn(b" 400 ", raw.recv(4096))
raw.close()
malformed = socket.create_connection(("127.0.0.1", server.server_address[1]), timeout=2)
malformed.sendall((
"POST /v1/responses HTTP/1.1\r\nHost: localhost\r\n"
f"Authorization: Bearer {KEY}\r\nContent-Type: application/json\r\n"
"Content-Length: 7\r\n\r\n{broken"
).encode())
self.assertIn(b" 400 ", malformed.recv(4096))
malformed.close()
headers = {**self.authorized(), "Content-Type": "application/json", "Content-Length": str(gateway.MAX_BODY + 1)}
status, _headers, _body = self.request(server, "POST", "/v1/responses", None, headers)
self.assertEqual(status, 413)
self.assertEqual(provider.calls, [])
def test_query_endpoint_and_non_sse_upstream_are_rejected(self):
provider = FakeProvider([FakeResponse(headers={"Content-Type": "application/json"})])
server = self.start_server(provider)
status, _headers, _body = self.request(server, "POST", "/v1/responses?debug=1", self.valid(), self.authorized())
self.assertEqual(status, 404)
status, _headers, body = self.request(server, "POST", "/v1/responses", self.valid(), self.authorized())
self.assertEqual(status, 502)
self.assertIn(b"upstream_content_type_invalid", body)
def test_nonstream_returns_actual_completed_response_with_function_call(self):
output = [{"type": "function_call", "call_id": "call", "name": "artifactRead", "arguments": "{}", "namespace": "affine"}]
expected, event = completed_response(output)
upstream = FakeResponse([event[:19], event[19:]])
provider = FakeProvider([upstream])
server = self.start_server(provider)
status, headers, body = self.request(server, "POST", "/v1/responses", self.valid(stream=False), self.authorized())
self.assertEqual(status, 200)
self.assertEqual(json.loads(body), expected)
self.assertEqual(headers["Cache-Control"], "no-store")
self.assertTrue(upstream.closed)
sent = provider.calls[-1][1]
self.assertIs(sent["stream"], True)
self.assertIs(sent["store"], False)
def test_missing_upstream_content_type_requires_valid_completed_sse(self):
expected, event = completed_response()
for payload, expected_status in ((event, 200), (b"not an SSE response", 502)):
with self.subTest(expected_status=expected_status):
provider = FakeProvider([FakeResponse([payload], headers={})])
server = self.start_server(provider)
status, _headers, body = self.request(server, "POST", "/v1/responses", self.valid(stream=False), self.authorized())
self.assertEqual(status, expected_status)
if status == 200:
self.assertEqual(json.loads(body), expected)
else:
self.assertIn(b"upstream_stream_interrupted", body)
def test_nonstream_collects_done_items_when_completed_output_is_empty(self):
items = [
{"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "OK"}]},
{"type": "function_call", "call_id": "call", "name": "affine_probe", "arguments": "{}"},
]
_response, completed = completed_response([])
events = [
("data: " + json.dumps({"type": "response.output_item.done", "output_index": index, "item": item}) + "\n\n").encode()
for index, item in enumerate(items)
]
provider = FakeProvider([FakeResponse(events + [completed], headers={})])
server = self.start_server(provider)
status, _headers, body = self.request(server, "POST", "/v1/responses", self.valid(stream=False), self.authorized())
self.assertEqual(status, 200)
self.assertEqual(json.loads(body)["output"], items)
def test_nonstream_failure_and_interruption_are_non_200_sanitized(self):
failed = b'event: response.failed\ndata: {"type":"response.failed","response":{"status":"failed","error":{"message":"private"}}}\n\n'
for upstream in (FakeResponse([failed]), FakeResponse([b"event: response.created\ndata: {\"type\":\"response.created\"}\n\n"])):
with self.subTest(chunks=upstream.chunks):
provider = FakeProvider([upstream])
server = self.start_server(provider)
status, _headers, body = self.request(server, "POST", "/v1/responses", self.valid(), self.authorized())
self.assertEqual(status, 502)
self.assertNotIn(b"private", body)
def test_stream_relays_complete_failure_and_interruption_without_fake_success(self):
_response, completed = completed_response()
failed = b'event: response.failed\ndata: {"type":"response.failed","response":{"status":"failed"}}\n\n'
interrupted = b'event: response.output_text.delta\ndata: {"type":"response.output_text.delta","delta":"x"}\n\n'
for payload, expected in ((completed, b"response.completed"), (failed, b"response.failed"), (interrupted, b"upstream_stream_interrupted")):
with self.subTest(expected=expected):
provider = FakeProvider([FakeResponse([payload])])
server = self.start_server(provider)
status, headers, body = self.request(server, "POST", "/v1/responses", self.valid(stream=True), self.authorized())
self.assertEqual(status, 200)
self.assertEqual(headers["Content-Type"], "text/event-stream")
self.assertIn(expected, body)
if expected != b"response.completed":
self.assertNotIn(b"response.completed", body)
def test_upstream_status_and_allowlisted_code_preserved_without_body_reflection(self):
upstream = FakeResponse(status=429, data={"error": {"code": "rate_limit_exceeded", "message": "private account detail"}})
provider = FakeProvider([upstream])
server = self.start_server(provider)
status, _headers, body = self.request(server, "POST", "/v1/responses", self.valid(), self.authorized())
self.assertEqual(status, 429)
self.assertIn(b"rate_limit_exceeded", body)
self.assertNotIn(b"private account detail", body)
def test_stream_disconnect_closes_upstream(self):
class Endless(FakeResponse):
def iter_content(self, chunk_size=1):
for _index in range(10000):
yield b'event: response.output_text.delta\ndata: {"type":"response.output_text.delta","delta":"xxxxxxxxxxxxxxxx"}\n\n'
time.sleep(0.001)
upstream = Endless()
provider = FakeProvider([upstream])
server = self.start_server(provider)
connection = socket.create_connection(("127.0.0.1", server.server_address[1]), timeout=2)
body = json.dumps(self.valid(stream=True)).encode()
connection.sendall((
"POST /v1/responses HTTP/1.1\r\nHost: localhost\r\n"
f"Authorization: Bearer {KEY}\r\nContent-Type: application/json\r\nContent-Length: {len(body)}\r\n\r\n"
).encode() + body)
connection.recv(512)
connection.close()
deadline = time.time() + 2
while not upstream.closed and time.time() < deadline:
time.sleep(0.01)
self.assertTrue(upstream.closed)
if __name__ == "__main__":
unittest.main()
+238
View File
@@ -0,0 +1,238 @@
diff --git a/packages/frontend/core/src/blocksuite/ai/components/ai-chat-input/ai-chat-input.ts b/packages/frontend/core/src/blocksuite/ai/components/ai-chat-input/ai-chat-input.ts
--- a/packages/frontend/core/src/blocksuite/ai/components/ai-chat-input/ai-chat-input.ts
+++ b/packages/frontend/core/src/blocksuite/ai/components/ai-chat-input/ai-chat-input.ts
@@ -860,7 +860,7 @@
control: this.trackOptions?.control,
reasoning: this._isReasoningActive,
toolsConfig: this.aiToolsConfigService.config.value,
- routeTargetId: this.aiModelService.modelId.value,
+ ...this.aiModelService.getSelection(),
userInfo: {
userId: userInfo?.id,
userName: userInfo?.name,
diff --git a/packages/frontend/core/src/blocksuite/ai/runtime/chat/runtime.ts b/packages/frontend/core/src/blocksuite/ai/runtime/chat/runtime.ts
--- a/packages/frontend/core/src/blocksuite/ai/runtime/chat/runtime.ts
+++ b/packages/frontend/core/src/blocksuite/ai/runtime/chat/runtime.ts
@@ -30,6 +30,10 @@
private createSessionPromise: Promise<
CopilotChatHistoryFragment | null | undefined
> | null = null;
+ private readonly sessionSelections = new Map<
+ string,
+ Pick<AIChatSendOptions, 'profileId' | 'modelId' | 'routeTargetId'>
+ >();
private snapshot: AIChatSnapshot;
constructor(private readonly options: RuntimeOptions) {
@@ -69,6 +73,7 @@
this.createSessionPromise = null;
this.createSessionPromiseKey = null;
this.streamAbortController?.abort();
+ this.sessionSelections.clear();
this.listeners.clear();
}
@@ -389,6 +394,10 @@
this.updateScopeSelection({ syncing: false });
}
+ const selection = options.profileId && options.modelId
+ ? { profileId: options.profileId, modelId: options.modelId }
+ : { routeTargetId: options.routeTargetId ?? this.snapshot.composer.routeTargetId };
+ this.sessionSelections.set(session.sessionId, selection);
const stream = (await this.options.request.executeAction('chat', {
workspaceId: this.snapshot.scope.workspaceId,
docId:
@@ -407,8 +416,7 @@
],
reasoning: options.reasoning ?? this.snapshot.composer.reasoning,
toolsConfig: options.toolsConfig ?? this.snapshot.composer.toolsConfig,
- routeTargetId:
- options.routeTargetId ?? this.snapshot.composer.routeTargetId,
+ ...selection,
isRootSession: options.isRootSession,
where: options.where,
control: options.control,
@@ -474,6 +482,7 @@
workspaceId: this.snapshot.scope.workspaceId,
sessionId: this.snapshot.activeSessionId,
liveEditorContext,
+ ...this.sessionSelections.get(this.snapshot.activeSessionId),
retry: true,
stream: true,
signal: this.streamAbortController.signal,
diff --git a/packages/frontend/core/src/blocksuite/ai/runtime/chat/actions.ts b/packages/frontend/core/src/blocksuite/ai/runtime/chat/actions.ts
--- a/packages/frontend/core/src/blocksuite/ai/runtime/chat/actions.ts
+++ b/packages/frontend/core/src/blocksuite/ai/runtime/chat/actions.ts
@@ -16,6 +16,8 @@
reasoning?: boolean;
toolsConfig?: unknown;
routeTargetId?: string;
+ profileId?: string;
+ modelId?: string;
userInfo?: {
userId?: string;
userName?: string;
diff --git a/packages/frontend/core/src/modules/ai-button/services/models.ts b/packages/frontend/core/src/modules/ai-button/services/models.ts
--- a/packages/frontend/core/src/modules/ai-button/services/models.ts
+++ b/packages/frontend/core/src/modules/ai-button/services/models.ts
@@ -1,4 +1,7 @@
-import { getCopilotRouteOptionsQuery } from '@affine/graphql';
+import {
+ getCopilotRouteOptionsQuery,
+ workspaceByokSettingsQuery,
+} from '@affine/graphql';
import { signal } from '@preact/signals-core';
import { Service } from '@toeverything/infra';
@@ -13,7 +16,24 @@
category: string;
version: string;
available: boolean;
+ profileId?: string;
+ modelId?: string;
}
+
+export type AIModelSelection =
+ | { routeTargetId?: undefined; profileId?: undefined; modelId?: undefined }
+ | { routeTargetId: string; profileId?: undefined; modelId?: undefined }
+ | { routeTargetId?: undefined; profileId: string; modelId: string };
+
+const isPermissionDenied = (error: unknown) =>
+ typeof error === 'object' &&
+ error !== null &&
+ 'isStatus' in error &&
+ typeof error.isStatus === 'function' &&
+ error.isStatus(403);
+
+const supportsText = (capability: { input: string[]; output: string[] }) =>
+ capability.input.includes('text') && capability.output.includes('text');
export class AIModelService extends Service {
readonly modelId = signal<string | undefined>(undefined);
@@ -31,7 +51,9 @@ export class AIModelService extends Service {
super();
const subscription = subscriptionService.subscription.ai$.subscribe(() => {
if (this.workspaceId && this.routeId) {
- this.load(this.workspaceId, this.routeId).catch(console.error);
+ this.load(this.workspaceId, this.routeId).catch(() =>
+ console.error('Failed to load AI models')
+ );
}
});
this.disposables.push(() => subscription.unsubscribe());
@@ -43,13 +65,26 @@ export class AIModelService extends Service {
this.routeId = routeId;
this.models.value = [];
this.modelId.value = undefined;
- this.load(workspaceId, routeId).catch(console.error);
+ this.load(workspaceId, routeId).catch(() =>
+ console.error('Failed to load AI models')
+ );
}
resetModel() {
this.setModel(undefined);
}
+ getSelection(): AIModelSelection {
+ const model = this.models.value.find(
+ candidate => candidate.id === this.modelId.value && candidate.available
+ );
+ if (!model) return {};
+ if (model.profileId && model.modelId) {
+ return { profileId: model.profileId, modelId: model.modelId };
+ }
+ return { routeTargetId: model.id };
+ }
+
setModel(modelId: string | undefined) {
if (!this.workspaceId || !this.routeId) return;
if (
@@ -67,18 +102,42 @@
private async load(workspaceId: string, routeId: string) {
const requestId = ++this.requestId;
- const result = await this.gqlService.gql({
- query: getCopilotRouteOptionsQuery,
- variables: { promptName: routeId },
- });
+ const to = new Date();
+ const from = new Date(to.getTime());
+ from.setDate(from.getDate() - 30);
+ const [managedResponse, byokResponse] = await Promise.allSettled([
+ this.gqlService.gql({
+ query: getCopilotRouteOptionsQuery,
+ variables: { promptName: routeId },
+ }),
+ this.gqlService
+ .gql({
+ query: workspaceByokSettingsQuery,
+ variables: {
+ id: workspaceId,
+ from: from.toISOString(),
+ to: to.toISOString(),
+ },
+ })
+ .catch(error => {
+ if (isPermissionDenied(error)) return undefined;
+ throw error;
+ }),
+ ]);
if (requestId !== this.requestId) return;
- const options = result.currentUser?.copilot?.routeOptions;
- if (!options) {
- this.models.value = [];
- this.modelId.value = undefined;
- return;
- }
- this.models.value = options.choices.map(choice => {
+ if (byokResponse.status === 'rejected') {
+ console.error('Failed to load workspace BYOK models');
+ throw byokResponse.reason;
+ }
+ if (managedResponse.status === 'rejected') {
+ console.error('Failed to load managed AI models');
+ }
+ const managedResult =
+ managedResponse.status === 'fulfilled' ? managedResponse.value : undefined;
+ const byokResult =
+ byokResponse.status === 'fulfilled' ? byokResponse.value : undefined;
+ const options = managedResult?.currentUser?.copilot?.routeOptions;
+ const managedModels = options?.choices.map(choice => {
const [category] = choice.displayName.split(' ');
return {
id: choice.id,
@@ -87,7 +146,31 @@
version: choice.displayName.slice(category.length + 1),
available: choice.available,
};
- });
+ }) ?? [];
+ const settings = byokResult?.workspace?.byokSettings;
+ const byokModels =
+ settings?.serverEntitled && settings.policy.enabled
+ ? settings.profiles.flatMap(profile => {
+ if (
+ !profile.enabled ||
+ !settings.policy.allowedProviders.includes(profile.provider)
+ ) {
+ return [];
+ }
+ return profile.definition.models
+ .filter(model => model.enabled && model.capabilities.some(supportsText))
+ .map(model => ({
+ id: `byok:${profile.profileId}:${encodeURIComponent(model.modelId)}`,
+ name: model.modelId,
+ category: model.modelId,
+ version: profile.name,
+ available: true,
+ profileId: profile.profileId,
+ modelId: model.modelId,
+ }));
+ })
+ : [];
+ this.models.value = [...managedModels, ...byokModels];
const selected = this.globalStateService.globalState.get<string>(
this.storageKey(workspaceId, routeId)
);
+11 -4
View File
@@ -14,7 +14,7 @@
openssl,
inputs,
system,
frontendPatches ? [ ./gitea-document-typography.patch ],
frontendPatches ? [ ./gitea-document-typography.patch ./byok-model-picker.patch ],
}:
let
@@ -151,7 +151,7 @@ let
runHook postConfigure
'';
frontend = stdenv.mkDerivation {
frontend = stdenv.mkDerivation ({
pname = "affine-frontend";
inherit version src yarnOfflineCache;
missingHashes = ./missing-hashes.json;
@@ -188,13 +188,20 @@ let
cp -R packages/frontend/apps/mobile/dist "$out/mobile"
runHook postInstall
'';
};
} // lib.optionalAttrs (builtins.elem ./byok-model-picker.patch frontendPatches) {
doCheck = true;
checkPhase = ''
runHook preCheck
AFFINE_SOURCE_DIR="$PWD" ${nodejs}/bin/node ${../../test/package/affine/test/model-picker.cjs}
runHook postCheck
'';
});
frontendStatic = runCommand "affine-frontend-static-${version}" {
inherit version;
passthru = { inherit revision; };
meta = {
description = "Source-built AFFiNE web assets with document typography patches";
description = "Source-built AFFiNE web assets with typography and BYOK model selection";
license = [ lib.licenses.mit lib.licenses.mpl20 ];
platforms = [ "x86_64-linux" ];
};
+1
View File
@@ -150,6 +150,7 @@ in {
deploy = pkgs.callPackage ./deploy { inherit inputs; };
element-web = pkgs.callPackage ./element-web { pnpm = giteaPkgs.pnpm_10; };
shellplot = pkgs.callPackage ./shellplot {};
affine-chatgpt = pkgs.callPackage ./affine-chatgpt {};
gitea-kanban-tui = pkgs.callPackage ./gitea-kanban-tui rust.commonArgs;
routine-server = pkgs.callPackage ./routine-server rust.commonArgs;
routine-tui = pkgs.callPackage ./routine-tui rust.commonArgs;