Files
hearth/package/affine-chatgpt/test/test_affine_chatgpt.py
T
yukkop 50c4efc09b
runner nix smoke / nix label and flake smoke (push) Failing after 1m12s
gpt in affine
2026-11-01 11:21:28 +00:00

707 lines
28 KiB
Python

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()